# -*- coding: utf-8 -*-
# Gotacı, gnome için adsl kota gösterme aracıdır.
 # Copyright (C), 2009 Oğuzhan Eroğlu <oguzhan@oguzhaneroglu.com>
 # This program is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.

 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.

from threading import Thread
import re
import urllib
import pycurl
import gtk
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

from settingsWindow import *

gtk.gdk.threads_init()
class quotaWindow(object):
	def __init__(self):
		self.window = gtk.Window()
		self.window.set_title("Kota")
		self.window.resize(310, 160)
		self.window.set_position(gtk.WIN_POS_CENTER)

		self.window.connect("hide", self.deleteclose)

		self.cont = gtk.Fixed()
		self.window.add(self.cont)
		self.cont.show()

		self.not_error = True

		if config.sections().__len__() != 0:
			try:
				self.name = config.get("user", "name")
				self.password = config.get("user", "password")
			except:
				sw = settingsWindow()
				sw.show()
				self.not_error = False
				return None
			Thread(target=self.showCaptcha, args=()).start()

	def showCaptcha(self):
		self.body = StringIO()

		def header(buf):
			# Print header data to stderr
			sys.stderr.write(buf)
		self.c = pycurl.Curl()
		self.c.setopt(self.c.USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)")
		self.c.setopt(self.c.URL, 'http://adslkota.ttnet.com.tr/adslkota/jcaptcha')
		self.c.setopt(pycurl.HEADERFUNCTION, header)
		self.c.setopt(pycurl.COOKIEJAR, "cookie.txt")
		self.c.setopt(pycurl.COOKIEFILE, "cookie.txt")
		self.c.setopt(self.c.WRITEFUNCTION, self.body.write)
		self.c.perform()
		self.content = self.body.getvalue()

		open("captcha.jpg", "w").write(self.content)

		self.image = gtk.Image()
		self.image.set_from_file("captcha.jpg")
		self.image.show()
		self.cont.put(self.image, 5, 15)

		# captcha girişi
		self.vcaptcha = gtk.Entry()
		self.cont.put(self.vcaptcha, 5, 125)
		self.vcaptcha.show()

		self.okbutton = gtk.Button("Tamam")
		self.okbutton.show()
		self.cont.put(self.okbutton, 165, 123)
		self.okbutton.connect("clicked", self.getQuota)

	def getQuota(self, event):
		print "..."
		Thread(target=self.getQuota_, args=()).start()
	def getQuota_(self):
		self.captcha = str(self.vcaptcha.get_text())
		pf = {"dispatch":"login",
		"userName":self.name,
		"password":self.password,
		"captchaResponse":self.captcha,
		"lang":"tr"}

		self.c.setopt(self.c.URL, 'http://adslkota.ttnet.com.tr/adslkota/loginSelf.do')
		self.c.setopt(self.c.POSTFIELDS, urllib.urlencode(pf))
		self.c.setopt(pycurl.COOKIEFILE, "cookie.txt")
		self.c.setopt(pycurl.COOKIEJAR, "cookie.txt")
		self.c.setopt(self.c.VERBOSE, 1)
		self.c.setopt(self.c.WRITEFUNCTION, self.body.write)
		self.c.perform()

		self.c.setopt(self.c.URL, "http://adslkota.ttnet.com.tr/adslkota/confirmAgreement.do?dispatch=agree")
		self.c.setopt(pycurl.COOKIEFILE, "cookie.txt")
		self.c.setopt(pycurl.COOKIEJAR, "cookie.txt")
		self.c.setopt(self.c.WRITEFUNCTION, self.body.write)
		self.c.perform()

		self.c.setopt(self.c.URL, "http://adslkota.ttnet.com.tr/adslkota/viewTransfer.do?dispatch=entry")
		self.c.setopt(pycurl.COOKIEFILE, "cookie.txt")
		self.c.setopt(pycurl.COOKIEJAR, "cookie.txt")
		self.c.setopt(self.c.WRITEFUNCTION, self.body.write)
		self.c.perform()

		self.quota_html = self.body.getvalue()
		self.showQuota()

	def showQuota(self):
		self.window.resize(125, 100)

		self.vcaptcha.hide()
		self.image.hide()
		self.okbutton.hide()

		html = self.quota_html
		try:
			kota_tablo = re.findall("(<tr class=\"odd\">.*)<center>.*<font style.\"color..365F",
			html.replace("\n", "*n*"))[0].replace("*n*", "\n")
		except:
			self.c.close()
			os.remove("cookie.txt")
			os.remove("captcha.jpg")
			return 0

		kotalar = re.findall("<td width.\"100\">(.*)</td>", kota_tablo)
		sonkota = []
		for i in range(4, 9):
			if "<br" in kotalar[i]:
				sonkota.append(re.findall("\(.*\)", kotalar[i])[0])
			else:
				sonkota.append(kotalar[i])

		self.label = gtk.Label()
		self.label.set_use_markup(True)
		self.label.set_markup("<b>%s %s</b>\n<b>Download:</b> %s\n<b>Upload:</b> %s" % (sonkota[1], sonkota[0], sonkota[3], sonkota[2]))
		self.label.show()
		self.cont.put(self.label, 10, 10)

		self.closebutton = gtk.Button("Tamam")
		self.closebutton.show()
		self.cont.put(self.closebutton, 50, 65)

		self.closebutton.connect("clicked", self.close)

		self.c.close()
		os.remove("cookie.txt")
		os.remove("captcha.jpg")

	def deleteclose(self, event):
		if os.path.exists("cookie.txt"):
			self.c.close()
			os.remove("cookie.txt")
			os.remove("captcha.jpg")

	def close(self, event):
		self.window.hide()

	def show(self):
		if self.not_error: self.window.show()